const fs = require('fs')
const path = require('path')

/**
 * 获得model路径
 */
function getModelPath() {
  return `${path.resolve('models')}`
}
/**
 * 创建目录
 */
function buildDirs(path) {
  return new Promise((resolve, reject) => {
    const exist = fs.existsSync(path)
    if (!exist) {
      fs.mkdir(path, (error) => {
        reject(error)
      })
    }
    setTimeout(() => {
      resolve()
    }, 500)
  })
}

/**
 * 创建文件
 */
function createFile(filepath, content) {
  return new Promise((resolve, reject) => {
    if (!fs.existsSync(filepath)) {
      fs.writeFile(filepath, content, (err) => {
        if (err) {
          reject(err)
        } else {
          setTimeout(() => {
            resolve()
          }, 500)
        }
      })
    } else {
      fs.unlink(filepath, (err) => {
        if (err) {
          reject(err)
        } else {
          setTimeout(() => {
            fs.writeFile(filepath, content, (err) => {
              if (err) {
                reject(err)
              } else {
                setTimeout(() => {
                  resolve()
                }, 500)
              }
            })
          }, 500)
        }
      })
    }
  })
}

exports.buildDirs = buildDirs
exports.createFile = createFile
exports.getModelPath = getModelPath
